/**
 * 
 * @param reducer 
 * @param enhancer 在store中，已经调用了applaymiddleware（logger, thunk）方法此时是他的返回值：craeteStore => reducer => {}
 * @returns 
 */
export default function createStore(reducer: Function, enhancer: Function) {

    if(enhancer) {
        return enhancer(createStore)(reducer)
    }

    let currentState: any = undefined

    let callbacks:any[] = []

    function getState() {
        return currentState
    }

    function dispatch(action: IAction) {
        currentState = reducer(currentState, action)
        callbacks.forEach(cb => {
            cb()
        })
        return action
    }

    function subscribe(cb:Function) {
        callbacks.push(cb)
        return () => {
            let idx = callbacks.findIndex(v => v === cb)
            callbacks.splice(idx, 1)
        }
    }

    dispatch({ type: Symbol() })

    return { 
        getState,
        dispatch,
        subscribe,
    }
}